package com.example.springboot.config;

import com.example.springboot.component.LoginHandlerInterceptor;
import com.example.springboot.component.MyLocalResolver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.*;

/**
 * 说明：用来拦截请求，并转发到相应的页面。
 */
@Configuration
public class MyWebConfig implements WebMvcConfigurer {
    /**
     * 方式一：
     * 相当于
     * @RequestMapping("/other")
     * public String login(){
     *     return "login";
     * }
     * @param registry
     */
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/other").setViewName("login");
    }


    /**
     * 方式二：
     * @return
     */
    @Bean
    public WebMvcConfigurer webMvcConfigurer(){
        WebMvcConfigurer configurer = new WebMvcConfigurer() {
            @Override
            public void addViewControllers(ViewControllerRegistry registry) {
                registry.addViewController("/login.html").setViewName("login");
                registry.addViewController("/index.html").setViewName("index");
            }

//            @Override
//            public void addInterceptors(InterceptorRegistry registry) {
//                registry.addInterceptor(new LoginHandlerInterceptor()).excludePathPatterns("/user/login","/","/login.html");
//            }

            /**
             * 静态资源的管理  springboot 2.0 之后版本要进行控制
             * @param registry
             */
            @Override
            public void addResourceHandlers(ResourceHandlerRegistry registry) {
                //静态资源
                registry.addResourceHandler("/static").addResourceLocations("classpath:/static/**");
            }

            /**
             * 跨域请求处理
             * @param registry
             */
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/cors/**")
                        .allowedOrigins("*")
                        .allowedHeaders("*")
                        .allowedMethods("*")
                        .maxAge(1800);
            }
        };
        return configurer;
    }

    /**
     * 国际化引入
     * @return
     */
    @Bean
    public LocaleResolver localeResolver(){
        return new MyLocalResolver();
    }
}
